package com.youwu.demo04.BSTCP;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class TCPServer {

    public static void main(String[] args) throws IOException {
        ServerSocket server = new ServerSocket(8080);
        Socket socket = server.accept();
        InputStream is = socket.getInputStream();

        // 把is网络字节输入流对象，转换为字符缓冲输入流
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String line = br.readLine();
        String[] split = line.split(" ");
        String htmlPath = split[1].substring(1);

        // 创建一个本地字节输入流，构造方法中绑定要读取的html路径
        FileInputStream fis = new FileInputStream(htmlPath);
        // 使用socket获取网络字节输出流OutputStream
        OutputStream os = socket.getOutputStream();

        // 写入HTTP协议响应头，固定写法
        os.write("HTTP/1.1 200 OK\r\n".getBytes());
        os.write("Content-Type:text/html\r\n".getBytes());
        // 必须要写入空行，否则浏览器不解析
        os.write("\r\n".getBytes());

        // 一读一写复制文件，把服务读取的html文件回写到客户端
        int len = 0;
        byte[] bytes = new byte[1024];
        while (-1 != (len = fis.read(bytes))) {
            os.write(bytes, 0, len);
        }

        fis.close();
        socket.close();
        server.close();
    }
}
